package com.wuye.controller;

import com.wuye.model.User;
import com.wuye.model.UserAddress;
import com.wuye.model.option.*;
import com.wuye.repository.*;
import com.wuye.web.ST;
import com.wuye.web.SessionHandler;
import com.wuye.web.UserSession;
import com.wuye.weixin.QyWeixin;
import com.wuye.weixin.WeixinException;
import com.wuye.weixin.WeixinManager;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by jiawenlong on 2016/8/1.
 * <p/>
 * SQL：获取每个问题的每个答案的个数
 * select contT.id ,sum(CASE contT.answer when 1 then  contT.cont else 0 end)as answer1 ,sum(CASE contT.answer when 2 then  contT.cont else 0 end)as answer2 ,sum(CASE contT.answer when 3 then  contT.cont else 0 end)as answer3
 * from (select count(*) as cont,answer,c.id from testC,(SELECT id from testC ) c  where questionId=c.id GROUP BY answer,c.id ORDER BY c.id) contT GROUP BY contT.id
 */
@Controller
@RequestMapping("/option")
public class OptionController {
    private Log log = LogFactory.getLog(this.getClass());
    @Autowired
    UserOptionRepository userOptionRepository;
    @Autowired
    SessionHandler sessionHandler;
    @Autowired
    QuestionFormRepository questionFormRepository;
    @Autowired
    QuestionGroupRepository questionGroupRepository;
    @Autowired
    QuestionRepository questionRepository;
    @Autowired
    QuestionnaireRepository questionnaireRepository;
    @Autowired
    UserRepository userRepository;
    @Autowired
    UserAnswersRepository userAnswersRepository;
    @Autowired
    QuestionAnswerRepository questionAnswerRepository;

    /**
     * 前台页面获取问卷
     *
     * @param model
     * @param paperId
     * @return
     */
    @ResponseBody
    @RequestMapping("getPaper.jspa")
    public String getPaper(HttpSession session,Model model, @RequestParam(value = "id", defaultValue = "-1") long paperId) {


        Questionnaire paper = questionnaireRepository.findOne(paperId);
        if (null == paper) {
            return ST.dataNotExists.toJson();
        }
        UserSession userSession = sessionHandler.getUserSession(session);
        if(userSession!=null) {
            List<UserAnswers> userAnswers = userAnswersRepository.findByUserIdAndQuestionnaireId(userSession.getUserId(), paperId);
            if (userAnswers.size() > 0) {
                return ST.paperHasFinished.toJson();
            }
        }
        Date now = new Date();
        if (now.getTime() < paper.getPublishTime().getTime()) {
            log.info("==================问卷还没有发布===================");
            return ST.dataNotExists.toJson();
        } else if (now.getTime() > paper.getEndTime().getTime()) {
            return ST.paperHasEnd.toJson();
        }
        org.json.JSONObject jo = ST.ok.getJsonObject();
        QuestionForm questionForm = questionFormRepository.findOne(paper.getFormId());
        jo.put("paperName", paper.getName());
        jo.put("paperId", paper.getId());
        if (questionForm != null) {
            List<QuestionGroup> groups = questionGroupRepository.findByFormIdOrderByIdAsc(questionForm.getId());
            List<Question> questions = questionRepository.findByFormIdOrderByIdAsc(questionForm.getId());
            List<QuestionGroupAndQuestionWrap> groupAndQuestions = new ArrayList<>();
            for (QuestionGroup g : groups) {
                QuestionGroupAndQuestionWrap qg = new QuestionGroupAndQuestionWrap(g);
                List<Question> tempQs = new ArrayList<>();
                for (Question q : questions) {
                    if (g.getId() == q.getGroupId()) {
                        tempQs.add(q);
                    }
                }
                qg.setQuestions(tempQs);
                groupAndQuestions.add(qg);
            }
            jo.put("groups", groupAndQuestions);
        }
        return jo.toString();
    }

    /**
     * 提交问卷
     * questionAnswer格式： answers:[{questionId:XXX,answer:XXX,mark:XXXX}]
     */
    @ResponseBody
    @RequestMapping(value = "submitPaper.jspa", method = RequestMethod.POST)
    public String submitPaper(HttpSession session, @RequestParam(value = "paperId", defaultValue = "-1") long paperId,
                              @RequestParam(value = "remark", defaultValue = "") String remark,
                              @RequestParam(value = "answers", defaultValue = "") String answers
                              ) throws WeixinException {
        Questionnaire questionnaire = questionnaireRepository.findOne(paperId);
        if (questionnaire == null) {
            log.info("========================问卷不存在========================");
            return ST.dataNotExists.toJson();
        }
        Date now = new Date();
        if (now.getTime() < questionnaire.getPublishTime().getTime()) {
            log.info("==================问卷还没有发布===================");
            return ST.dataNotExists.toJson();
        } else if (now.getTime() > questionnaire.getEndTime().getTime()) {
            log.info("========================问卷已到截至日期，不能再次提交答卷========================");
            return ST.paperHasEnd.toJson();
        }
        UserSession userSession = sessionHandler.getUserSession(session);
        User user = userRepository.findByUserId(userSession.getUserId());
        JSONArray ja = JSONArray.fromObject(answers);
        List<UserAnswers> uas = userAnswersRepository.findByUserIdAndQuestionnaireId(userSession.getUserId(),paperId);
        if(uas.size()>0){
            return ST.paperHasFinished.toJson();
        }
        UserAnswers userAnswers = new UserAnswers();
        userAnswers.setName(userSession.getUserName());
        userAnswers.setAddTime(new Date());
        userAnswers.setDeptId(user.getDepartment());
        userAnswers.setDeptName(user.getDepartmentName());
        userAnswers.setPhone(user.getCellPhone());
        userAnswers.setQuestionnaireId(questionnaire.getId());
        userAnswers.setUserId(user.getUserId());
        userAnswers.setRemark(remark);
        userAnswersRepository.save(userAnswers);
        for(int i=0;i<ja.size();i++){
            JSONObject jo = (JSONObject) ja.get(i);
            QuestionAnswer qa = new QuestionAnswer();
            qa.setUserId(user.getUserId());
            qa.setQuestionnaireId(questionnaire.getId());
            qa.setAnswer(jo.getInt("answer"));
            qa.setMark(jo.getString("mark"));
            qa.setQuestionId(jo.getLong("questionId"));
            qa.setUserAnswerId(userAnswers.getId());
            questionAnswerRepository.save(qa);
        }
        questionnaire.setUserNum(questionnaire.getUserNum() + 1);
        questionnaireRepository.save(questionnaire);

        return ST.ok.toJson();
    }
}